import { Injectable } from '@angular/core';
import * as jsencrypt from "jsencrypt";
// import {Http} from "@angular/http";
import { HttpService, HTTPMethods } from "http-service";
import { UtilsService } from "./utils.services";
import {Storage} from "@ionic/storage";
import {API} from "../models/api-path-extension";
import { Observable } from 'rxjs';

// declare namespace jsencrypt {

declare class JSEncrypt {

  constructor();

  JSEncrypt(): any;

  setKey(val: string): string;

  encrypt(val: string): string;

  decrypt(val): string;
}
// }

@Injectable()
export class EncryptService {

  private _key = "";

  private _jsencrypt: JSEncrypt;

  constructor(
              // public env: Config,
              public util: UtilsService,
              public storage: Storage,
              public httpService: HttpService) {
    this._jsencrypt = new jsencrypt.JSEncrypt();
  }

  public getPublic() {
   return Observable.create( (subcriber) => {
    if (this._key) {
      this._jsencrypt.setKey(this._key);
      subcriber.next();
      subcriber.complete();
    } else {
      this.storage.get('publicKey').then((key) => {
        if (key) {
          this._key = key;
          this._jsencrypt.setKey(this._key);
          subcriber.next();
          subcriber.complete();
        } else {
          this.getPublicKey().subscribe((res) => {
            if (res.code === 200) {
              this._key = res.data;
              this.storage.set('publicKey', res.data);
              this._jsencrypt.setKey(this._key);
              subcriber.next();
              subcriber.complete();
            } else {
              this.util.tip(res.message);
              subcriber.error();
            }
          }, (err) => {
            this.util.tip(err.message);
            subcriber.error();
          });
        }
      }, (err) => {
        console.error(err);
        subcriber.error();
      });
    }
    });
    
  }

  public encrypt(val: string) {

    return this._jsencrypt.encrypt(val);
  }

  // Todo comment now beacause it's useless
  /*public decrypt(val: string) {

    return this._jsencrypt.decrypt(val);
  }*/

  public getPublicKey() {
    return this.httpService.fetchWithPath(new API().path({ path: "publickey", method: HTTPMethods.Get }));
    // return this.http.get(this.env.getEndpoint('publickey')).map(res => res.json());
  }
}
